package prototype.greatestsage;

import java.io.*;
import java.util.Date;

/**
 * 齐天大圣
 *
 * @author cctv
 */
public class TheGreatestSage extends Monkey implements Cloneable,Serializable{

    /**
     * 金箍棒
     */
    private GoldRingedStaff staff;

    /**
     * 从石头里蹦出来
     */
    public TheGreatestSage() {
        staff = new GoldRingedStaff();
        birthday = new Date();
        height = 100;
        weight = 50;
        System.out.println("clone不走构造方法 只是字节流复制-----------");
    }

    /**
     * 分身
     *
     * @return
     */
    @Override
    public Object clone() {
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois =null;
        try {
//            return super.clone()// 默认浅克隆，只克隆八大基本数据类型和String（byte、short、int、long、float、double、char、boolean、string）
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            TheGreatestSage copy = (TheGreatestSage) ois.readObject();
            // clone 不走构造函数
            copy.birthday = new Date();
            return copy;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    public void change() {
        this.getStaff().setHeight(101);
        this.getStaff().setTgs(new TheGreatestSage());
        TheGreatestSage copy = (TheGreatestSage) clone();
        System.out.println("本尊的生日是" + getBirthday().getTime());
        System.out.println("分身的生日是" + copy.getBirthday().getTime());
        System.out.println("本尊和分身是否是同一个对象" + (this == copy));
        System.out.println("本尊的金箍棒和分身的金箍棒是否是同一个对象" + (this.getStaff() == copy.getStaff()));
        System.out.println(getStaff().getHeight());
        System.out.println(copy.getStaff().getHeight());
        System.out.println(copy.getStaff().getTgs().getStaff().getHeight());
        copy.getStaff().grow();
        System.out.println(getStaff().getHeight());
        System.out.println(copy.getStaff().getHeight());
        System.out.println(copy.getStaff().getTgs().getStaff().getHeight());

    }


    public GoldRingedStaff getStaff() {
        return staff;
    }

    public void setStaff(GoldRingedStaff staff) {
        this.staff = staff;
    }
}
